/**
 * PHOSIDE: PHosphorylation Site IDentification Engine.
 * Copyright 2009 Digital Biology Lab, University of Missouri.
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 3 of the License, or (at your option) any later
 * version. <p/> This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more
 * details.
 */

package phoside.io.fasta.parser;

import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

import phoside.util.StaticFinalValues;
import phoside.util.StringUtil;

/**
 *
 * @author gjj
 */
public class DefaultPhosphoSequenceParser
        extends DefaultSequenceParser
        implements PhosphoSequenceParser {
    protected final String token;
    protected final String tokenOct;
    
//    public DefaultPhosphoSequenceParser() {
//        this("#");
//    }

    public DefaultPhosphoSequenceParser(final String token) {
        if (token==null) {
            throw new IllegalArgumentException("Null token");
        }
        this.token = token;
        this.tokenOct = StringUtil.toOct(token);
    }

    @Override
    public void parse(final String sequence) {
        if (sequence==null) {
            throw new NullPointerException();
        }

        // remove spaces first
        String seq = sequence.replaceAll("[0-9\\p{Space}]", "");

        Set<Integer> sites = new HashSet();

        TreeSet<Integer> ix = StringUtil.findAll(seq, token, false);
        int count = 0;
        for (int i:ix) {
            int site = i-1-count*token.length();
            sites.add(site);
            count++;
        }

//        Pattern p = Pattern.compile("\\[p(.)\\]");
//        Matcher m = p.matcher(seq);
//        int start = 0;
//        int nsites = 0;
//        while (m.find(start)) {
//            int site = m.start() - nsites*3;
//            sites.add(site);
//            start = m.end();
//            nsites++;
//        }

        if (!sites.isEmpty()) {
            setSites(sites);
//            m.reset();
//            super.parse(m.replaceAll("$1"));
            super.parse(seq.replaceAll(tokenOct, ""));
        } else {
            invalidate();
            super.parse(seq);
        }
    }
    
    /**
     *
     * @return
     */
    public Set<Integer> getSites() {
        return (Set<Integer>)getField(StaticFinalValues.SITES);
    }

    protected void setSites(Set<Integer> sites) {
        addField(StaticFinalValues.SITES, sites);
    }

    protected void invalidate() {
        removeField(StaticFinalValues.SITES);
    }
}
